package service

import (
	"exam12_23/config"
	"exam12_23/internal/api/request"
	"exam12_23/internal/models/dao"
	"strconv"
	"time"
)

func CreateFriend(friend *request.Friend, userId int) string {
	var user *dao.User
	var friends *dao.Friend
	var friends1 *dao.Friend
	tx := config.DB.Begin()
	Num := "create_friend" + strconv.Itoa(friend.FriendId)
	tx.Model(&dao.User{}).Where("id=?", friend.FriendId).Limit(1).Find(&user)
	if user.ID == 0 {
		tx.Rollback()
		return "对方不存在"
	}
	tx.Model(&dao.Friend{}).Where("user_id=? and friend_id=?", friend.FriendId, userId).Limit(1).Find(&friends)
	if friends.ID != 0 {
		tx.Rollback()
		return "你们已经添加过好友了"
	}
	tx.Model(&dao.Friend{}).Where("user_id=? and friend_id=?", userId, friend.FriendId).Limit(1).Find(&friends1)
	if friends1.ID != 0 {
		tx.Rollback()
		return "你们已经添加过好友了"
	}
	tx.Commit()
	config.Rdb.Set(config.Ctx, Num, userId, time.Hour*24)
	return ""
}

func Yes(userId int) string {
	var friends *dao.Friend
	var friends1 *dao.Friend
	tx := config.DB.Begin()
	Num := "create_friend" + strconv.Itoa(userId)
	get := config.Rdb.Get(config.Ctx, Num).Val()
	if get == "" {
		return "没好友申请"
	}
	friendId, _ := strconv.Atoi(get)
	tx.Model(&dao.Friend{}).Where("user_id=? and friend_id=?", friendId, userId).Limit(1).Find(&friends)
	if friends.ID != 0 {
		tx.Rollback()
		return "你们已经添加过好友了"
	}
	tx.Model(&dao.Friend{}).Where("user_id=? and friend_id=?", userId, friendId).Limit(1).Find(&friends1)
	if friends1.ID != 0 {
		tx.Rollback()
		return "你们已经添加过好友了"
	}
	fr := dao.Friend{
		UserId:   userId,
		FriendId: friendId,
	}
	err := tx.Model(&dao.Friend{}).Create(&fr).Error
	if err != nil {
		tx.Rollback()
		return "好友添加失败"
	}
	fr1 := dao.Friend{
		UserId:   friendId,
		FriendId: userId,
	}
	err = tx.Model(&dao.Friend{}).Create(&fr1).Error
	if err != nil {
		tx.Rollback()
		return "好友添加失败"
	}
	tx.Commit()
	config.Rdb.Del(config.Ctx, Num)
	return ""
}

func No(userId int) string {
	Num := "create_friend" + strconv.Itoa(userId)
	get := config.Rdb.Get(config.Ctx, Num).Val()
	if get == "" {
		return "没好友申请"
	}
	config.Rdb.Del(config.Ctx, Num)
	return "拒绝好友申请成功"
}
